import { sendEmailCode } from '@/services/user';
import { ResponseCode } from '@/utils/request';
import { LockOutlined } from '@ant-design/icons';
import { ProFormCaptcha } from '@ant-design/pro-components';
import { message } from 'antd';
import type { FormInstance } from 'antd/es/form/Form';

interface Props {
  formInstance: FormInstance<{ email: string }>;
}

// 验证码组件
const UserCodeCaptcha: React.FC<Props> = ({ formInstance }) => {
  return (
    <ProFormCaptcha
      fieldProps={{
        size: 'large',
        prefix: <LockOutlined className="prefix-icon" />,
      }}
      captchaProps={{
        size: 'large',
      }}
      placeholder="请输入验证码"
      captchaTextRender={(timing, count) => {
        if (timing) {
          return `${count} 秒后重新获取`;
        }
        return '获取验证码';
      }}
      name="code"
      rules={[
        {
          required: true,
          message: '请输入验证码！',
        },
      ]}
      onGetCaptcha={async () => {
        const email = formInstance.getFieldValue('email');
        const { code, message: msg } = await sendEmailCode(email);
        if (code === ResponseCode.Fail) {
          message.warning(msg || '验证码发送失败');
          return;
        }
        message.success('验证码发送成功！');
      }}
    />
  );
};

export default UserCodeCaptcha;
